<template>
  <div
    class="personnel-info fixed z-10"
    :class="[visible ? 'visible opacity-100' : 'invisible opacity-0']"
    :style="{
      ...selfPosition,
    }"
    @mouseenter="onEnter"
    @mouseleave="onLeave"
    @click.capture="onClickSelf"
  >
    <!-- userId 获取个人信息时 loading 占位 -->
    <div
      v-if="loading || hasError"
      class="loading-placeholder shadow-lg flex justify-center items-center"
      style="width: 360px; height: 192px"
    >
      <div v-if="hasError" class="teld-color-gray">
        {{ /*加载失败*/ qLangComment.loadFailed }}
      </div>
      <t-inner-loading :showing="loading">
        <t-spinner size="28px" color="primary" />
      </t-inner-loading>
    </div>

    <div
      v-else
      class="
        content-wrapper rounded border-2 border-solid border-gray-100
        flex flex-col  mt-5 shadow-lg bg-white
      "
      style="width: 360px;"
    >
      <!-- 上部 -->
      <div class="flex p-3" style="">
        <user-avatar
          :image-url="record.Avatar"
          :class-list="['w-20 h-20']"
          class="absolute top-0"
        ></user-avatar>

        <!-- 头像右侧主信息：姓名和公司 -->
        <div
          class="flex flex-col justify-center ml-4"
          style="margin-left: 100px"
        >
          <div class="flex items-center">
            <span class="mr-2 text-base font-semibold flex items-center">
              {{ record.RealName }}
            </span>
            <span class="" style="line-height: 0">
              <!-- 注：性别字段接口是返回的中文！这里没有办法使用多语言 -->
              <gender-male v-if="record.Gender === '男'" class="w-4 h-4" />
              <gender-female
                v-else-if="record.Gender === '女'"
                class="w-4 h-4"
              />
            </span>
          </div>

          <div class="teld-color-gray">{{ record.CompanyName }}&nbsp;</div>
        </div>
      </div>

      <!-- 下部 -->
      <div class="flex-1 teld-bg-color-gray">
        <div
          class="info-card max-h-60 bg-white py-3 px-5 rounded overflow-y-auto mt-1"
        >
          <div class="flex">
            <div class="teld-color-gray w-20">
              {{ /*手机号*/ qLangComment.mobile }}
            </div>
            <span v-if="record._showFullMobile_">{{ record.Mobile }}</span>
            <span v-else class="flex-1 break-all">
              {{ record._mobileMask_ }}
              <span
                ref="viewMobileRef"
                class="ml-2 text-xs teld-theme-color cursor-pointer"
                @click.capture.prevent.stop="onClickMobileMask(record)"
              >
                {{ /*查看*/ qLangComment.view }}
              </span>
            </span>
          </div>
          <div class="flex">
            <div class="teld-color-gray w-20">
              {{ /*邮箱*/ qLangComment.email }}
            </div>
            <span class="flex-1 break-all">{{
              record.Email || qLangComment.simpleNoData
            }}</span>
          </div>
          <div class="flex">
            <div class="teld-color-gray w-20">
              {{ /*账号*/ qLangComment.account }}
            </div>
            <span class="flex-1 break-all">{{
              record.Account || qLangComment.simpleNoData
            }}</span>
          </div>
          <div class="flex">
            <div class="teld-color-gray w-20">
              {{ /*部门*/ qLangComment.department }}
            </div>
            <span class="flex-1 break-all">
              {{ joinDepartmentName(record) || qLangComment.simpleNoData }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// Components
import UserAvatar from '../../components/user-avatar/index.vue';
import GenderFemale from '../../components/svg-icons/gender-female.vue';
import GenderMale from '../../components/svg-icons/gender-male.vue';

// Utils
import { mobileMask } from '../../hooks';
import demoUserInfo from 't/mock/mock-data/comment/SYS_UserMgr_GetSysUserById.js';
import { getSysUserInfoById } from '../../hooks/api';

const MARGIN_GAP = 12;

export default {
  name: 'PersonnelInfoPopup',
  inject: ['qLangComment'],
  props: {
    model: {
      type: Object,
      default: null,
    },
    userId: {
      type: String,
      default: null,
    },
    targetElement: {
      type: HTMLElement,
      default: null,
    },
  },
  components: {
    UserAvatar,
    GenderFemale,
    GenderMale,
  },
  data() {
    return {
      loading: false,
      hasError: false,
      record: {},
      selfPosition: {
        top: null,
        right: null,
        bottom: null,
        left: null,
      },
    };
  },
  watch: {
    model(nVal) {
      this.init();
    },
    userId(nVal) {
      this.init();
    },
  },
  computed: {
    visible() {
      return this.model || this.userId;
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.hasError = false;
      if (this.userId) {
        this.getUserInfo();
      } else if (this.model) {
        this.record = {
          ...this.model,
          _mobileMask_: mobileMask(this.model.Mobile),
          _showFullMobile_: false,
        };
        this.updatePosition();
      }
    },
    // 只有 id 时从接口获取
    async getUserInfo() {
      try {
        /**
         * 【WARNING】这个接口没有 state 那一层，直接 data
         */
        // const { data } = await this.$utils.sgApi.getDataAsync({
        //   url: this.$utils.common.getServiceUrl('SYS_UserMgr_GetSysUserById '),
        //   data: { userId: JSON.stringify(this.userId) },
        // });
        // const data = demoUserInfo;
        const res = await getSysUserInfoById(this.userId);
        this.loading = true;

        if (!res) {
          this.hasError = true;
          return;
        }

        // Mock
        // setTimeout(() => {
        //   this.record = demoUserInfo;
        //   this.loading = false;
        // }, 500);
        this.record = {
          ...res,
          _mobileMask_: mobileMask(res.Mobile),
          _showFullMobile_: false,
        };
        this.updatePosition();
      } catch (error) {
        console.log(error);
        this.hasError = true;
      } finally {
        setTimeout(() => {
          this.loading = false;
        }, 300);
      }
    },
    updatePosition() {
      if (!this.targetElement || !(this.targetElement instanceof HTMLElement))
        return;
      const targetRect = this.targetElement.getBoundingClientRect();
      const vh = window.innerHeight;
      const vw = window.innerWidth;
      const popupRect = this.$el.getBoundingClientRect();
      const position = { left: null, top: null, bottom: null, right: null };

      // 判断边界
      // --超出左侧边界--
      if (targetRect.left - MARGIN_GAP - popupRect.width < 0) {
        // 小屏幕情况下右侧也空间不足的话
        if (targetRect.right + MARGIN_GAP + popupRect.width > vw) {
          position.right = '0';
        } else {
          position.left = `${targetRect.right + MARGIN_GAP }px`;
        }
      } else {
        position.left = `${targetRect.left - MARGIN_GAP - popupRect.width }px`;
      }

      // --超出上侧边界--
      if (targetRect.top - MARGIN_GAP - popupRect.height / 2 < 0) {
        position.top = '0';
      } else {
        // 当正好在中间位置输入时就可能造成上下两边都空间不足的情况：下边也不足的时候
        if (targetRect.bottom < popupRect.height) {
          position.top = '0';
        } else if (targetRect.top + popupRect.height / 2 > vh) {
          position.bottom = '0';
        } else {
          position.top = `${targetRect.top - popupRect.height / 2}px`;
        }
      }

      this.selfPosition = position;
      console.log('userInfo position', position);
    },
    joinDepartmentName(item) {
      const { DepartmentName, WorkgroupName } = item;
      const arr = [];
      DepartmentName && arr.push(DepartmentName);
      WorkgroupName && arr.push(WorkgroupName);
      return arr.join('-');
    },
    onClickMobileMask(item) {
      item._showFullMobile_ = true;
    },
    onEnter() {
      this.$emit('change-visible', false);
    },
    onLeave() {
      this.$emit('change-visible', true);
    },
    onClickSelf(e) {
      if (e.target !== this.$refs.viewMobileRef) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }
    },
  },
};
</script>

<style lang="scss">
.personnel-info {
  /* 定义过渡效果 */
  transition:
    top 0.3s,
    bottom 0.3s,
    left 0.3s,
    right 0.3s,
    opacity 0.5s,
    visibility 0.8s;
}
</style>
